package com.app.signing.utils;

import android.content.Intent;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.app.signing.data.SpManager;
import com.app.signing.data.bean.SigningSetting;
import com.app.signing.view.login.LoginStates;
import com.app.signing.view.signin.SignInActivity;

/**
 * 包名： com.amap.locationservicedemo
 * <p>
 * 创建时间：2016/10/27
 * 项目名称：LocationServiceDemo
 *
 * @author guibao.ggb
 * @email guibao.ggb@alibaba-inc.com
 * <p>
 * 类说明：后台服务定位
 * <p>
 * <p>
 * modeified by liangchao , on 2017/01/17
 * update:
 * 1. 只有在由息屏造成的网络断开造成的定位失败时才点亮屏幕
 * 2. 利用notification机制增加进程优先级
 * </p>
 */
public class LocationService extends NotiService {

    private static final String TAG = "LocationService";

    private AMapLocationClient mLocationClient;

    private int locationErrorCount = 0;

    /**
     * 处理息屏关掉wifi的delegate类
     */
    private IWifiAutoCloseDelegate mWifiAutoCloseDelegate = new WifiAutoCloseDelegate();

    /**
     * 记录是否需要对息屏关掉wifi的情况进行处理
     */
    private boolean mIsWifiCloseable = false;

    private SigningSetting signingSetting;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        applyNotiKeepMech(); //开启利用notification提高进程优先级的机制

        if (mWifiAutoCloseDelegate.isUseful(getApplicationContext())) {
            mIsWifiCloseable = true;
            mWifiAutoCloseDelegate.initOnServiceStarted(getApplicationContext());
        }

        startLocation();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        unApplyNotiKeepMech();
        stopLocation();

        super.onDestroy();
    }

    /**
     * 启动定位
     */
    void startLocation() {
        stopLocation();

        if (null == mLocationClient) {
            mLocationClient = new AMapLocationClient(this.getApplicationContext());
        }

        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        // 使用连续
        mLocationOption.setOnceLocation(false);
        mLocationOption.setLocationCacheEnable(false);
        // 每10秒定位一次
        int value = Integer.valueOf(SpManager.Companion.getINSTANCE().readSigningInterval());
        mLocationOption.setInterval(value * 1000);
        // 地址信息
        mLocationOption.setNeedAddress(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.setLocationListener(locationListener);
        mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    void stopLocation() {
        if (null != mLocationClient) {
            mLocationClient.stopLocation();
        }
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            //发送结果的通知
            sendLocationBroadcast(aMapLocation);
            checkSigningEnd(aMapLocation);

            if (!mIsWifiCloseable) {
                return;
            }

            if (aMapLocation.getErrorCode() == AMapLocation.LOCATION_SUCCESS) {
                mWifiAutoCloseDelegate.onLocateSuccess(getApplicationContext(),
                        PowerManagerUtil.getInstance().isScreenOn(getApplicationContext()),
                        NetUtil.getInstance().isMobileAva(getApplicationContext()));
            } else {
                mWifiAutoCloseDelegate.onLocateFail(getApplicationContext(),
                        aMapLocation.getErrorCode(),
                        PowerManagerUtil.getInstance().isScreenOn(getApplicationContext()),
                        NetUtil.getInstance().isWifiCon(getApplicationContext()));
            }
        }

        /**
         * 发送定位广播
         */
        private void sendLocationBroadcast(AMapLocation aMapLocation) {
            Intent mIntent = new Intent(SignInActivity.RECEIVER_LOCATION_ACTION);
            mIntent.putExtra("result",
                    new LocationResult(aMapLocation.getErrorCode(), aMapLocation.getLatitude(),
                            aMapLocation.getLongitude(), aMapLocation.getErrorInfo()));
            sendBroadcast(mIntent);
        }

        /**
         * 发送结束定位广播
         */
        private void sendSigningEndBroadcast() {
            Log.i(TAG, "sendSigningEndBroadcast: 发送结束广播-start");
            Intent mIntent = new Intent(SignInActivity.RECEIVER_SIGNING_END_ACTION);
            sendBroadcast(mIntent);
        }

        /**
         * 检查是否要发送结束签到广播
         * 1.普通占座模式下，超出签到范围
         * 2.定位失败超过5次
         */
        private void checkSigningEnd(AMapLocation aMapLocation) {
            if (aMapLocation.getErrorCode() != 0) {
                locationErrorCount++;
                // 定位失败超过5次,结束签到
                if (locationErrorCount > 5) {
                    sendSigningEndBroadcast();
                }
                return;
            }
            if (signingSetting == null) {
                signingSetting = SpManager.Companion.getINSTANCE().readSigningSetting();
            }
            // 计算当前定位点是否在签到范围内
            LatLng signingLatLng =
                    new LatLng(signingSetting.getLatitude(), signingSetting.getLongitude());
            LatLng locationLatLng =
                    new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            boolean isContains =
                    AMapUtils.calculateLineDistance(signingLatLng, locationLatLng) <= signingSetting
                            .getRadius();
            // 不在，同时是普通占座模式时，结束签到
            if (!isContains
                    && SpManager.Companion.getINSTANCE().readLoginStates()
                    == LoginStates.loginDefault) {
                sendSigningEndBroadcast();
            }
        }
    };
}
